//
//  DHCommunity_NoImageCell.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/5/31.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHCommunity_NoImageCell.h"
#import "DHHomepageViewController.h"
#import "DHCommunity_ImageCollectionCell.h"
#import "ImageCheckVC.h"
#import "DHHomepageViewController.h"
#import "DHUser_HomePageController.h"
#import "XLPhotoBrowser.h"

@interface DHCommunity_NoImageCell()<XLPhotoBrowserDelegate>


@end

@implementation DHCommunity_NoImageCell

- (NSArray *)itemArr{
    if (!_itemArr) {
        _itemArr = [NSArray array];
    }
    return _itemArr;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.headerImgView.layer.cornerRadius = self.headerImgView.height / 2;
    self.followView.layer.cornerRadius = self.followView.height / 2;
    self.followView.layer.borderWidth = 1;
    self.followView.layer.borderColor = [[UIColor colorWithHexString:@"#9A9A9A"] CGColor];
    
    [self.headerImgView bk_whenTapped:^{
        if ([Login isLogin]) {
            if ([[Login curLoginUser]._id isEqualToString:[[self.model objectForKey:@"owner"] objectForKey:@"_id"]]) {
                DHUser_HomePageController *vc = [[DHUser_HomePageController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                [self.viewController.navigationController pushViewController:vc animated:YES];
            }else{
                DHHomepageViewController *vc = [[DHHomepageViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                [self.viewController.navigationController pushViewController:vc animated:YES];
                vc.userDic = [self.model objectForKey:@"owner"];
            }
        }else{
            DHHomepageViewController *vc = [[DHHomepageViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.viewController.navigationController pushViewController:vc animated:YES];
            vc.userDic = [self.model objectForKey:@"owner"];
        }
    }];
    
    [self.headerImgView bk_whenTapped:^{
        DHHomepageViewController *vc = [[DHHomepageViewController alloc] init];
        vc.userDic = [self.model objectForKey:@"owner"];
        vc.hidesBottomBarWhenPushed = YES;
        [self.viewController.navigationController pushViewController:vc animated:YES];
    }];
    
    WeakSelf(weakSelf)
    [self.followButton bk_addEventHandler:^(id sender) {
        if ([[[weakSelf.model objectForKey:@"owner"] objectForKey:@"subscribed"] boolValue]) {
            NSString *user_id = [[self.model objectForKey:@"owner"] objectForKey:@"_id"];
            NSDictionary *params = @{@"user_id":user_id,@"subscribe":[NSNumber numberWithBool:NO]};
            [[DHNetAPIClient shareDHNetAPIClient] request_social_subscribeWithParams:params andBlock:^(id data, NSError *error) {
                NSMutableDictionary *owner = [NSMutableDictionary dictionaryWithDictionary:[weakSelf.model objectForKey:@"owner"]];
                [owner setValue:@(0) forKey:@"subscribed"];
                [weakSelf.model setValue:owner forKey:@"owner"];
                weakSelf.followTextLabel.text = @"关注";
                weakSelf.followImgView.image = [UIImage imageNamed:@"follow"];
            }];
        }else{
            NSString *user_id = [[weakSelf.model objectForKey:@"owner"] objectForKey:@"_id"];
            NSDictionary *params = @{@"user_id":user_id,@"subscribe":[NSNumber numberWithBool:YES]};
            [[DHNetAPIClient shareDHNetAPIClient] request_social_subscribeWithParams:params andBlock:^(id data, NSError *error) {
                NSMutableDictionary *owner = [NSMutableDictionary dictionaryWithDictionary:[self.model objectForKey:@"owner"]];
                [owner setValue:@(1) forKey:@"subscribed"];
                [weakSelf.model setValue:owner forKey:@"owner"];
                weakSelf.followTextLabel.text = @"已关注";
                weakSelf.followImgView.image = [UIImage imageNamed:@"followed"];
            }];
        }
        [weakSelf routerEventWithName:@"follow_changed" userInfo:@{@"row":@(self.row),@"model":weakSelf.model}];
    } forControlEvents:UIControlEventTouchUpInside];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"DHCommunity_ImageCollectionCell" bundle:nil] forCellWithReuseIdentifier:kDHCommunity_ImageCollectionCell];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *view = [super hitTest:point withEvent:event];
    if ([view isKindOfClass:[UICollectionView class]]) {
        return self;
    }
    return [super hitTest:point withEvent:event];
}

- (void)updateCell:(NSDictionary *)dic{
    self.model = [NSMutableDictionary dictionaryWithDictionary:dic];
    [self.headerImgView dh_setImageURLString:[[self.model objectForKey:@"owner"] objectForKey:@"photo"]];
    self.nameLabel.text = [[self.model objectForKey:@"owner"] objectForKey:@"nickname"];
    self.disLabel.text = [[self.model objectForKey:@"owner"] objectForKey:@"title"];
    self.communityTextLabel.text = [self.model objectForKey:@"content"];
    self.likeLabel.text = [NSString stringWithFormat:@"%@",[self.model objectForKey:@"nice_count"]];
    self.commentLabel.text = [NSString stringWithFormat:@"%@",[self.model objectForKey:@"comments_count"]];
    NSDate *date = [NSDate dateWithServerISOString:[self.model objectForKey:@"createdAt"] format:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
    self.timeLabel.text = [NSDate stringFromDate:date withFormat:@"yyyy/MM/dd HH:mm"];
    
    if ([[dic objectForKey:@"niced_by_self"] boolValue]) {
        [self.niceImageView setImage:[UIImage imageNamed:@"magazine_like.png"]];
    }else{
        [self.niceImageView setImage:[UIImage imageNamed:@"magazine_unlike.png"]];
    }
    
    CGFloat contentHeight = [[self.model objectForKey:@"content"] heightForFont:[UIFont systemFontOfSize:14] width:kScreenWidth - 20];
    self.textLayoutHeight.constant = contentHeight + 5;
    
    if ([[[self.model objectForKey:@"owner"] objectForKey:@"_id"] isEqualToString:[Login curLoginUser]._id]) {
        self.followView.hidden = YES;
    }else{
        self.followView.hidden = NO;
        if ([[[self.model objectForKey:@"owner"] objectForKey:@"subscribed"] boolValue]) {
            self.followTextLabel.text = @"已关注";
            self.followImgView.image = [UIImage imageNamed:@"followed"];
        }else{
            self.followTextLabel.text = @"关注";
            self.followImgView.image = [UIImage imageNamed:@"follow"];
        }
    }
    
    self.itemArr = [self.model objectForKey:@"images"];
    
    if (self.itemArr.count == 0) {
        self.collectionViewHeightLayout.constant = 0;
    }else if (self.itemArr.count > 0 && self.itemArr.count <= 3){
        self.collectionViewHeightLayout.constant = 128;
    }else if (self.itemArr.count > 3 && self.itemArr.count <= 6){
        self.collectionViewHeightLayout.constant = 128 * 2 + 5;
    }else if (self.itemArr.count > 6 && self.itemArr.count <= 9){
        self.collectionViewHeightLayout.constant = 128 * 3 + 10;
    }
    
    [self.collectionView reloadData];
}

- (IBAction)niceAction:(id)sender {
    [[DHNetAPIClient shareDHNetAPIClient] request_social_post_niceWithParams:@{@"post_id":[self.model objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
        NSInteger currentNiceCount = [self.likeLabel.text integerValue];
        if ([[self.model objectForKey:@"niced_by_self"] boolValue]) {
            [self.model setObject:@(NO) forKey:@"niced_by_self"];
            [self.model setObject:@(currentNiceCount - 1) forKey:@"nice_count"];
            [self.niceImageView setImage:[UIImage imageNamed:@"magazine_unlike.png"]];
            self.likeLabel.text = [NSString stringWithFormat:@"%li",currentNiceCount - 1];
        }else{
            [self.model setObject:@(YES) forKey:@"niced_by_self"];
            [self.model setObject:@(currentNiceCount + 1) forKey:@"nice_count"];
            [self.niceImageView setImage:[UIImage imageNamed:@"magazine_like.png"]];
            self.likeLabel.text = [NSString stringWithFormat:@"%li",currentNiceCount + 1];
        }
        [self routerEventWithName:@"nice_changed" userInfo:@{@"row":@(self.row),@"model":self.model}];
    }];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma mark - UICollectionViewDataSource and UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemArr.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DHCommunity_ImageCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHCommunity_ImageCollectionCell forIndexPath:indexPath];
    NSString *model = [self.itemArr objectAtIndex:indexPath.row];
    [cell.imgViwe dh_setImageURLString:model];
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return (CGSize){(kScreenWidth - 34 - 15)/3,128};
}

// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:self.itemArr currentImageIndex:indexPath.row];
    browser.browserStyle = XLPhotoBrowserStyleIndexLabel; // 微博样式
    
    // 设置长按手势弹出的地步ActionSheet数据,不实现此方法则没有长按手势
    [browser setActionSheetWithTitle:@"" delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存图片",nil];
//    ImageCheckVC *vc = [[ImageCheckVC alloc] initWithImgsArr:self.itemArr andIndex:indexPath.row];
//    [self.viewController presentViewController:vc animated:YES completion:nil];
}

#pragma mark - XLPhotoBrowserDelegate
- (void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex
{
    // do something yourself
    switch (actionSheetindex) {
        case 0: // 保存
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
            [browser saveCurrentShowImage];
        }
            break;
        default:
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
        }
            break;
    }
}


@end
